package com.iwhalecloud.bss.kite.cucc.order.accept.chain.impl;

import com.iwhalecloud.bss.kite.cucc.order.accept.chain.AbstractOrderHandler;
import com.iwhalecloud.bss.kite.cucc.order.accept.constructor.DataConstructorManager;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.change.KiteInstChange;
import com.iwhalecloud.bss.kite.manager.inst.change.KiteRelChange;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * <Description> <br>
 * 订单受理流程： 实例对象组装
 *
 * @author xiao.xuzhang<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2020年2月13日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.order.accept.chain.impl <br>
 */
@Component
public class InstAssembleHandler extends AbstractOrderHandler {

    @Autowired
    IQuerySceneInstService querySceneInstService;

    @Override
    public void doHandle(OrderRequest orderRequest) {

        List<KiteInstChange> instChanges = loadInstChanges(orderRequest);
        List<KiteRelChange> relChanges = loadRelChanges(orderRequest);

        // 根据实例变动和关系变动构造实例对象
        DataConstructorManager.buildOrderRequest(orderRequest, instChanges, relChanges);
    }

    /**
     * Description: <br>
     * 加载实例变动信息
     *
     * @author xiao.xuzhang<br>
     * @taskId <br>
     * @param orderRequest
     * @return <br>
     */
    private List<KiteRelChange> loadRelChanges(OrderRequest orderRequest) {
        List<KiteRelChange> relChanges = new ArrayList<>();
        List<String> sceneInstIds = orderRequest.getSceneInstIds();

        if (sceneInstIds.size() == 1) {
            relChanges = querySceneInstService.listRelChanges(sceneInstIds.get(0));
        }
        else if (sceneInstIds.size() > 1) {
            relChanges = querySceneInstService.listMergeRelChanges(new HashSet<>(sceneInstIds),
                orderRequest.getCustId());
        }

        return relChanges;
    }

    /**
     * Description: <br>
     * 加载关系变动信息
     *
     * @author xiao.xuzhang<br>
     * @taskId <br>
     * @param orderRequest
     * @return <br>
     */
    private List<KiteInstChange> loadInstChanges(OrderRequest orderRequest) {
        List<KiteInstChange> instChanges = new ArrayList<>();
        List<String> sceneInstIds = orderRequest.getSceneInstIds();

        if (sceneInstIds.size() == 1) {
            instChanges = querySceneInstService.listInstChanges(sceneInstIds.get(0));
        }
        else if (sceneInstIds.size() > 1) {
            instChanges = querySceneInstService.listMergeInstChanges(new HashSet<>(sceneInstIds),
                orderRequest.getCustId());
        }

        return instChanges;
    }
}
